package com.palazzisoft.balonpie.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.palazzisoft.balonpie.dao.UserDao;
import com.palazzisoft.balonpie.entities.User;

@Component
public class BalonpieUserDetailService implements UserDetailsService {

	private UserDao userDao;
	
	@Autowired
	public BalonpieUserDetailService(UserDao userDao) {
		this.userDao = userDao;
	}
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = this.userDao.getUser(username);
		
		if (user == null) {
			throw new UsernameNotFoundException("Invalid User as trying to load");
		}
		
		UserDetails userDetail = new org.springframework.security.core.userdetails.User(
				user.getUserName(), user.getPassword(), AuthorityUtils.createAuthorityList(user
						.getRole()));
		
		return userDetail;
	}

}
